package com.tedu.manager;

import com.tedu.controller.MusicPlayer;
import com.tedu.show.GameConstants;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 音乐管理器 (单例)
 * 负责从配置文件加载音乐路径，并控制音乐播放
 */
public final class MusicManager {
    private static MusicManager musicManager;
    private final MusicPlayer musicPlayer;
    private final Map<String, String> musicPaths;
    private Properties pro;
    private int currentVolume = GameConstants.DEFAULT_MUSIC_VOLUME;

    private MusicManager() {
        this.musicPlayer = new MusicPlayer();
        this.musicPaths = new HashMap<>();
        this.pro = new Properties();
        loadMusicPaths();
    }

    public static synchronized MusicManager getInstance() {
        if (musicManager == null) {
            musicManager = new MusicManager();
        }
        return musicManager;
    }

    /**
     * 从 music.pro 文件加载所有音乐路径到 Map中
     */
    private void loadMusicPaths() {
        String configPath = "com/tedu/text/music.pro";
        try (InputStream is = getClass().getClassLoader().getResourceAsStream(configPath)) {
            if (is == null) {
                System.err.println("错误：找不到音乐配置文件: " + configPath);
                return;
            }
            pro.load(is);
            for (String key : pro.stringPropertyNames()) {
                musicPaths.put(key, pro.getProperty(key));
            }
        } catch (IOException e) {
            System.err.println("加载音乐配置文件时出错。");
            throw new RuntimeException();
        }
    }

    /**
     * 根据键名播放音乐
     * @param musicKey 配置文件中的键名
     * @param loop 是否循环
     */
    public void playMusic(String musicKey, boolean loop) {
        String path = musicPaths.get(musicKey);
        if (path != null && !path.isEmpty()) {
            musicPlayer.playMusic(path, loop);
            setVolume(this.currentVolume);
        } else {
            System.err.println("警告：在配置文件中找不到音乐键: " + musicKey);
        }
    }

    /**
     * 设置音量（百分比）
     * @param percentage 0 到 100
     */
    public void setVolume(int percentage) {
        this.currentVolume = Math.max(0, Math.min(100, percentage));
        float volumeFloat = this.currentVolume / 100.0F;
        musicPlayer.setVolume(volumeFloat);
    }

    /**
     * 获取当前音量百分比
     */
    public int getVolume() {
        return currentVolume;
    }

    /**
     * 停止当前所有音乐
     */
    public void stop() {
        musicPlayer.stopMusic();
    }
}
